from django.shortcuts import render

# Create your views here.
import time
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer, InvalidChannelLayerError, AcceptConnection, DenyConnection
from asgiref.sync import sync_to_async, async_to_sync


class ScView(WebsocketConsumer):
    def websocket_connect(self, message):
        print("有人来了")
        self.accept()

    def websocket_receive(self, message):
        print(message["text"])

        if message["text"] == "close":
            self.close()
            raise StopConsumer()
        self.send(message["text"])

    def websocket_disconnect(self, message):
        raise StopConsumer()


class AsyncScView(WebsocketConsumer):
    async def websocket_connect(self, message):
        print("有人来了")
        await self.accept()

    async def websocket_receive(self, message):
        print(message["text"])

        if message["text"] == "close":
            await self.close()
            raise StopConsumer()
        await self.send(message["text"])

    async def websocket_disconnect(self, message):
        raise StopConsumer()


demo = []


class qunChartView(WebsocketConsumer):

    def websocket_connect(self, message):
        print(self.scope)
        demo.append(self.scope["client"][1])
        print(demo)

        group = self.scope["url_route"]["kwargs"].get("pk")

        async_to_sync(self.channel_layer.group_add)(str(group), self.channel_name)

        self.accept()

    def websocket_receive(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")
        # {"type": "xx.oo", "message": message}  xx_oo方法，传message
        async_to_sync(self.channel_layer.group_send)(str(group), {"type": "xx.oo", "message": message})
        self.send(message["text"])

    def xx_oo(self, event):
        text = event["message"]["text"]
        self.send(text)  # 给组里每一个人回复

    def websocket_disconnect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")
        async_to_sync(self.channel_layer.group_discard)(str(group), self.channel_name)
        self.disconnect(message["code"])
        raise StopConsumer()

    def disconnect(self, code):
        demo.remove(self.scope["client"][1])
        print(demo)
        pass


class qunView(WebsocketConsumer):
    # groups表示群聊组，发消息的时候，选择群聊组的某个群进行发消息
    groups = ["23234234"]

    def websocket_connect(self, message):

        """
        Called when a WebSocket connection is opened.
        """
        try:
            for group in self.groups:
                async_to_sync(self.channel_layer.group_add)(group, self.channel_name)
        except AttributeError:
            raise InvalidChannelLayerError(
                "BACKEND is unconfigured or doesn't support groups"
            )
        try:
            print("连接1")
            self.connect()
        except AcceptConnection:
            print("连接2")
            self.accept()
        except DenyConnection:
            print("关闭1")
            self.close()


class skUserView(WebsocketConsumer):
    # groups 记录当前登陆的用户
    users = ["admin1", "admin2"]

    def websocket_connect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")

        async_to_sync(self.channel_layer.group_add)(group, self.channel_name)

        try:
            self.connect()
        except AcceptConnection:
            self.accept()
        except DenyConnection:
            self.close()

    ############# 只是消息收发使用，外部调用，
    # 当接收到消息时干什么事
    def websocket_receive(self, message):
        # message 为每次接受到的值 {'type': 'websocket.receive', 'text': 'erwerwerwerwer'}
        group = self.scope["url_route"]["kwargs"].get("pk")
        # 接收到的消息
        text = message["text"]
        # {"type": "xx.oo", "message": message}  xx_oo方法，传message
        # 调用要收到消息时要做的事
        async_to_sync(self.channel_layer.group_send)(group, {"type": "xx.oo", "text": text})
        # self.send(message["text"])

    # 干的事，单独拎出来
    def xx_oo(self, event):
        text = event["text"]
        self.send(text)  # 给group 里面，每一个链接，发消息

    ####################################################################

    def websocket_disconnect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")
        async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
        self.disconnect(message["code"])
        raise StopConsumer()

    def disconnect(self, code):
        print(code)
        pass

    def getMenu(self, event):
        text = event["text"]
        self.send(text)
        # 方法名，不加下划线(_)就可以直接写方法名
        # async_to_sync(channel_layer.group_send)("a965b28b-d282-4178-842c-78feb14bab06", {"type": "getMenu",
        # "text": '{"name": "1234"}'})
        pass


# 外部调用：
"""

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

channel_layer = get_channel_layer()


def send_msg():
    async_to_sync(channel_layer.group_send)("a965b28b-d282-4178-842c-78feb14bab06", {"type": "getMenu","text": '{"name": "1234"}'})
       

send_msg()

"""
